<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 每日记录</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <style>
        /* 基础样式 */
        body {
            background: linear-gradient(135deg, #4F46E5 0%, #6366F1 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 20px;
        }
        .login-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            padding: 2.5rem;
            width: 100%;
            max-width: 420px;
        }
        .form-input {
            transition: all 0.3s ease;
        }
        .form-input:focus {
            border-color: #4F46E5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        /* 标签页样式 */
        .tabs {
            display: flex;
            border-bottom: 1px solid #e5e7eb;
            margin-bottom: 2rem;
        }
        .tab {
            padding: 0.5rem 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            color: #6b7280;
            border-bottom: 2px solid transparent;
        }
        .tab.active {
            color: #4F46E5;
            border-bottom-color: #4F46E5;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }

        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 1em;
            height: 1em;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 二维码区域样式 */
        #qrCodeArea {
            text-align: center;
        }
        #qrCodeImg {
            width: 200px;
            height: 200px;
            margin: 20px auto;
            border: 1px solid #eee;
            padding: 10px;
            cursor: pointer; /* 鼠标悬停显示手型，提示可点击 */
            transition: transform 0.2s;
        }
        #qrCodeImg:hover {
            transform: scale(1.02); /*  hover时轻微放大，增强交互感 */
        }
        #qrStatusMsg {
            color: #666;
            margin: 10px 0;
            height: 24px;
        }
        .tips {
            color: #999;
            font-size: 14px;
        }
        /* 扫码成功提示样式 */
        .scanned {
            color: #10B981; /* 绿色表示已扫码 */
            font-weight: 500;
        }
    </style>
</head>
<body>
<div class="login-card">
    <!-- 页面标题 -->
    <div class="text-center mb-6">
        <i class="fa fa-book text-[#4F46E5] text-4xl mb-3"></i>
        <h2 class="text-2xl font-bold text-gray-800">每日记录 - 登录</h2>
        <p class="text-gray-500 mt-1">请选择登录方式</p>
    </div>

    <!-- 登录方式标签页 -->
    <div class="tabs">
        <div class="tab active" data-tab="password-login">账号密码登录</div>
        <div class="tab" data-tab="qr-login">扫码登录</div>
    </div>

    <!-- 1. 账号密码登录区域 -->
    <div class="tab-content active" id="password-login">
        <form id="loginForm" class="space-y-4">
            <div>
                <label for="username" class="block text-sm font-medium text-gray-700 mb-1">账号</label>
                <div class="relative">
                    <i class="fa fa-user absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    <input
                            type="text"
                            id="username"
                            name="username"
                            required
                            class="form-input w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none"
                            placeholder="请输入账号">
                </div>
            </div>

            <div>
                <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                <div class="relative">
                    <i class="fa fa-lock absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    <input
                            type="password"
                            id="password"
                            name="password"
                            required
                            class="form-input w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none"
                            placeholder="请输入密码">
                </div>
            </div>

            <!-- 密码登录错误提示 -->
            <div id="passwordErrorMsg" class="hidden text-red-500 text-sm text-center py-2"></div>

            <button
                    type="submit"
                    id="loginBtn"
                    class="w-full bg-[#4F46E5] hover:bg-[#4F46E5]/90 text-white font-medium py-3 px-4 rounded-lg transition-colors flex items-center justify-center"
            >
                <i class="fa fa-sign-in mr-2"></i>
                <span id="btnText">登录</span>
                <span id="btnLoading" class="ml-2 hidden"><span class="loading"></span></span>
            </button>
        </form>
    </div>

    <!-- 2. 扫码登录区域 -->
    <div class="tab-content" id="qr-login">
        <div id="qrCodeArea">
            <h3 class="text-lg font-medium text-gray-800 mb-2">扫码登录</h3>
            <p class="tips">点击下方二维码模拟APP扫码（测试用）</p> <!-- 提示可点击 -->
            <img id="qrCodeImg" src="" alt="二维码加载中...">
            <div id="qrStatusMsg" class="text-gray-600 mt-2">二维码生成中...</div>
            <p class="tips mt-4">二维码将在2分钟后刷新</p>
        </div>
        <!-- 扫码登录错误提示 -->
        <div id="qrErrorMsg" class="hidden text-red-500 text-sm text-center py-2 mt-4"></div>
    </div>
</div>

<script>
    // 全局变量：SSE连接（扫码登录用）
    let eventSource = null;
    // 固定的qrCodeId（根据需求设置）
    const FIXED_QR_CODE_ID = '952e5a31-4557-4da4-91d6-a88fc27e45e2';
    // 固定的userId（模拟APP登录用户）
    const FIXED_USER_ID = 'admin';

    document.addEventListener('DOMContentLoaded', () => {
        // 1. 标签页切换逻辑
        const tabs = document.querySelectorAll('.tab');
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                // 切换标签激活状态
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                // 切换内容区域
                const tabId = tab.getAttribute('data-tab');
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });
                document.getElementById(tabId).classList.add('active');

                // 切换到扫码登录时，初始化SSE连接
                if (tabId === 'qr-login' && !eventSource) {
                    initQrCodeSSE();
                }
                // 切换到密码登录时，关闭SSE连接（节省资源）
                if (tabId === 'password-login' && eventSource) {
                    eventSource.close();
                    eventSource = null;
                }
            });
        });

        // 2. 密码登录表单逻辑（保持不变）
        const loginForm = document.getElementById('loginForm');
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const passwordErrorMsg = document.getElementById('passwordErrorMsg');
        const loginBtn = document.getElementById('loginBtn');
        const btnText = document.getElementById('btnText');
        const btnLoading = document.getElementById('btnLoading');

        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            // 前端验证
            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();
            if (!username || !password) {
                showPasswordError('请输入账号和密码');
                return;
            }

            // 显示加载状态
            loginBtn.disabled = true;
            btnText.textContent = '登录中';
            btnLoading.classList.remove('hidden');
            passwordErrorMsg.classList.add('hidden');

            try {
                // 发送密码登录请求
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
                });

                const result = await response.json();
                if (result.code === 200 && result.token) {
                    // 登录成功：存储token并跳转
                    localStorage.setItem('token', result.token);
                    window.location.href = '/index.html';
                } else {
                    showPasswordError(result.msg || '账号或密码错误，请重试');
                }
            } catch (error) {
                console.error('密码登录失败:', error);
                showPasswordError('网络错误，请稍后重试');
            } finally {
                // 恢复按钮状态
                loginBtn.disabled = false;
                btnText.textContent = '登录';
                btnLoading.classList.add('hidden');
            }
        });

        // 3. 给二维码图片添加点击事件（模拟扫码）
        document.getElementById('qrCodeImg').addEventListener('click', simulateScan);
    });

    // 模拟扫码动作：点击二维码后调用后端接口
    async function simulateScan() {
        const qrStatusMsg = document.getElementById('qrStatusMsg');
        const qrErrorMsg = document.getElementById('qrErrorMsg');

        // 1. 显示“已扫码”状态
        qrStatusMsg.textContent = '已扫码，正在验证...';
        qrStatusMsg.classList.add('scanned'); // 添加绿色样式
        qrErrorMsg.classList.add('hidden');

        try {
            // 2. 调用后端扫码接口，携带固定参数
            const response = await fetch('/login/qrCode/scan', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `qrCodeId=${encodeURIComponent(FIXED_QR_CODE_ID)}&userId=${encodeURIComponent(FIXED_USER_ID)}`
            });

            const result = await response.json();
            if (result.code === '200') {
                // 3. 接口调用成功，显示验证中提示
                qrStatusMsg.textContent = '验证成功，正在登录...';
            } else {
                // 接口返回错误（如二维码过期）
                qrStatusMsg.textContent = '';
                showQrError(result.msg || '扫码验证失败');
            }
        } catch (error) {
            // 网络错误
            console.error('模拟扫码失败:', error);
            qrStatusMsg.textContent = '';
            showQrError('网络错误，扫码失败');
        }
    }

    // 3. 扫码登录SSE初始化（保持不变，确保二维码能正常加载）
    function initQrCodeSSE() {
        // 建立SSE连接
        eventSource = new EventSource('/login/qrCode');

        // 监听二维码更新事件
        eventSource.addEventListener('qrCodeUpdate', (event) => {
            try {
                const data = JSON.parse(event.data);
                document.getElementById('qrCodeImg').src = data.qrCodeSrc;
                document.getElementById('qrStatusMsg').textContent = data.message;
                document.getElementById('qrStatusMsg').classList.remove('scanned'); // 重置样式
                hideQrError();
            } catch (e) {
                console.error('解析二维码数据失败:', e);
                showQrError('二维码加载失败，请刷新');
            }
        });

        // 监听扫码登录成功事件（后端验证通过后）
        eventSource.addEventListener('loginSuccess', (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.code === '200') {
                    document.getElementById('qrStatusMsg').textContent = '登录成功，正在跳转...';
                    document.getElementById('qrStatusMsg').classList.add('scanned');
                    localStorage.setItem('token', data.token);
                    // 2秒后跳转首页
                    setTimeout(() => {
                        window.location.href = '/index.html';
                    }, 2000);
                }
            } catch (e) {
                console.error('解析登录成功事件失败:', e);
            }
        });

        // 处理SSE连接错误
        eventSource.onerror = (error) => {
            console.error('SSE连接错误:', error);
            showQrError('连接异常，请刷新页面');
            // 关闭异常连接
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
        };

        // 页面关闭时清理SSE连接
        window.onbeforeunload = () => {
            if (eventSource) {
                eventSource.close();
            }
        };
    }

    // 密码登录错误提示
    function showPasswordError(message) {
        const el = document.getElementById('passwordErrorMsg');
        el.textContent = message;
        el.classList.remove('hidden');
        setTimeout(() => el.classList.add('hidden'), 3000);
    }

    // 扫码登录错误提示
    function showQrError(message) {
        const el = document.getElementById('qrErrorMsg');
        el.textContent = message;
        el.classList.remove('hidden');
    }

    function hideQrError() {
        document.getElementById('qrErrorMsg').classList.add('hidden');
    }
</script>
</body>
</html>